using MediatR;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
using Work.API.Applications.Read.Commands;
using Work.API.Applications.Write.Commands;
using Work.API.Dtos.DrugManagement;
using Work.ErrorCode;

namespace Work.API.Controllers.DrugManagement
{
    /// <summary>
    /// 药品管理控制器
    /// 统一管理所有药品相关的接口：
    /// 1. 药品查看
    /// 2. 药品入库
    /// 3. 药品出库
    /// 4. 查看检药单
    /// 5. 查看已发药品
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DrugController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ILogger<DrugController> _logger;

        public DrugController(IMediator mediator, ILogger<DrugController> logger)
        {
            _mediator = mediator;
            _logger = logger;
        }

        #region 药品查看模块

        /// <summary>
        /// 获取药品列表（用于药品查看模块）
        /// 支持多条件搜索：药品名称、药品类型、价格范围等
        /// </summary>
        [HttpGet]
        public async Task<ApiResult<List<DrugDto>>> GetDrugs(
            string? drugName = null,
            string? drugType = null,
            string? costName = null,
            string? dosageForm = null,
            string? specification = null,
            decimal? minPurchasePrice = null,
            decimal? maxPurchasePrice = null,
            decimal? minSellingPrice = null,
            decimal? maxSellingPrice = null,
            bool onlyEnabled = true)
        {
            try
            {
                var query = new GetDrugsQuery
                {
                    DrugName = drugName,
                    DrugType = drugType,
                    CostName = costName,
                    DosageForm = dosageForm,
                    Specification = specification,
                    MinPurchasePrice = minPurchasePrice,
                    MaxPurchasePrice = maxPurchasePrice,
                    MinSellingPrice = minSellingPrice,
                    MaxSellingPrice = maxSellingPrice,
                    OnlyEnabled = onlyEnabled
                };
                return await _mediator.Send(query);
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, "查询药品列表失败");
                return new ApiResult<List<DrugDto>>
                {
                    Code = ApiEnum.失败,
                    Message = $"查询失败：{ex.Message}",
                    Data = new List<DrugDto>()
                };
            }
        }

        /// <summary>
        /// 根据药品ID查询入库记录（用于药品查看模块 - 查看药品入库记录）
        /// 支持时间范围筛选
        /// </summary>
        [HttpGet]
        public async Task<ApiResult<List<DrugInboundDto>>> GetDrugInboundRecordsByDrugId(
            int drugId,
            DateTime? startDate = null,
            DateTime? endDate = null)
        {
            try
            {
                var query = new GetDrugInboundRecordsByDrugIdQuery
                {
                    DrugId = drugId,
                    StartDate = startDate,
                    EndDate = endDate
                };
                return await _mediator.Send(query);
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, "查询药品入库记录失败");
                return new ApiResult<List<DrugInboundDto>>
                {
                    Code = ApiEnum.失败,
                    Message = $"查询失败：{ex.Message}",
                    Data = new List<DrugInboundDto>()
                };
            }
        }

        /// <summary>
        /// 根据药品ID查询出库记录（用于药品查看模块 - 查看药品出库记录）
        /// 支持时间范围筛选
        /// </summary>
        [HttpGet]
        public async Task<ApiResult<List<DrugOutboundDto>>> GetDrugOutboundRecordsByDrugId(
            int drugId,
            DateTime? startDate = null,
            DateTime? endDate = null)
        {
            try
            {
                var query = new GetDrugOutboundRecordsByDrugIdQuery
                {
                    DrugId = drugId,
                    StartDate = startDate,
                    EndDate = endDate
                };
                return await _mediator.Send(query);
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, "查询药品出库记录失败");
                return new ApiResult<List<DrugOutboundDto>>
                {
                    Code = ApiEnum.失败,
                    Message = $"查询失败：{ex.Message}",
                    Data = new List<DrugOutboundDto>()
                };
            }
        }

        #endregion

        #region 药品入库模块

        /// <summary>
        /// 创建药品（首次入库）
        /// 用于新增药品记录，同时创建入库记录
        /// </summary>
        [HttpPost]
        public async Task<ApiResult<int>> CreateDrug(CreateDrugCommand request)
        {
            try
            {
                return await _mediator.Send(request);
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, "创建药品失败");
                return new ApiResult<int>
                {
                    Code = ApiEnum.失败,
                    Message = $"创建失败：{ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 药品入库（再次入库）
        /// 用于增加现有药品的库存
        /// </summary>
        [HttpPost]
        public async Task<ApiResult<int>> InboundDrug(InboundDrugCommand request)
        {
            try
            {
                return await _mediator.Send(request);
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, "药品入库失败");
                return new ApiResult<int>
                {
                    Code = ApiEnum.失败,
                    Message = $"入库失败：{ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 更新药品信息
        /// 用于修改药品信息和库存信息
        /// </summary>
        [HttpPost]
        public async Task<ApiResult<int>> UpdateDrug(UpdateDrugCommand request)
        {
            try
            {
                return await _mediator.Send(request);
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, "更新药品失败");
                return new ApiResult<int>
                {
                    Code = ApiEnum.失败,
                    Message = $"更新失败：{ex.Message}",
                    Data = 0
                };
            }
        }

        #endregion

        #region 药品出库模块

        /// <summary>
        /// 药品出库（发药）
        /// 用于从库存中扣除药品，发药给患者
        /// </summary>
        [HttpPost]
        public async Task<ApiResult<int>> OutboundDrug(OutboundDrugCommand request)
        {
            try
            {
                return await _mediator.Send(request);
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, "药品出库失败");
                return new ApiResult<int>
                {
                    Code = ApiEnum.失败,
                    Message = $"出库失败：{ex.Message}",
                    Data = 0
                };
            }
        }

        #endregion

        #region 查看检药单模块

        /// <summary>
        /// 获取未打单处方明细列表（用于查看检药单模块 - 未打单列表）
        /// 查询已支付但未创建检药单的处方明细
        /// </summary>
        [HttpGet]
        public async Task<ApiResult<List<UnbilledPrescriptionDto>>> GetUnbilledPrescriptions(
            string? registrationNum = null,
            string? patientName = null,
            DateTime? startDate = null,
            DateTime? endDate = null,
            string? timeFilterType = null)
        {
            try
            {
                var query = new GetUnbilledPrescriptionsQuery
                {
                    RegistrationNum = registrationNum,
                    PatientName = patientName,
                    StartDate = startDate,
                    EndDate = endDate,
                    TimeFilterType = timeFilterType
                };
                return await _mediator.Send(query);
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, "查询未打单处方明细列表失败");
                return new ApiResult<List<UnbilledPrescriptionDto>>
                {
                    Code = ApiEnum.失败,
                    Message = $"查询失败：{ex.Message}",
                    Data = new List<UnbilledPrescriptionDto>()
                };
            }
        }

        /// <summary>
        /// 获取检药单列表（用于查看检药单模块 - 已打单未发药列表）
        /// 只返回已创建检药单但未发药的记录（IsDispensed=false）
        /// 支持按时间筛选（今天/本周/本月/今年/全部）和患者信息筛选
        /// </summary>
        [HttpGet]
        public async Task<ApiResult<List<InspectionListDto>>> GetInspectionList(
            string? registrationNum = null,
            string? patientName = null,
            string? inspectionStatus = null,
            DateTime? startDate = null,
            DateTime? endDate = null,
            string? timeFilterType = null)
        {
            try
            {
                // 只查询未发药的检药单（IsDispensed=false）
                var query = new GetInspectionListQuery
                {
                    RegistrationNum = registrationNum,
                    PatientName = patientName,
                    InspectionStatus = inspectionStatus,
                    IsDispensed = false, // 固定为false，只返回未发药的
                    StartDate = startDate,
                    EndDate = endDate,
                    TimeFilterType = timeFilterType
                };
                return await _mediator.Send(query);
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, "查询检药单列表失败");
                return new ApiResult<List<InspectionListDto>>
                {
                    Code = ApiEnum.失败,
                    Message = $"查询失败：{ex.Message}",
                    Data = new List<InspectionListDto>()
                };
            }
        }

        /// <summary>
        /// 创建检药单
        /// 当患者缴费后，处方明细状态变为"已支付"，系统可以创建检药单
        /// </summary>
        [HttpPost]
        public async Task<ApiResult<int>> CreateInspection(CreateInspectionCommand request)
        {
            try
            {
                return await _mediator.Send(request);
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, "创建检药单失败");
                return new ApiResult<int>
                {
                    Code = ApiEnum.失败,
                    Message = $"创建失败：{ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 更新检药单
        /// 用于更新检查状态、检查结果等信息
        /// </summary>
        [HttpPost]
        public async Task<ApiResult<int>> UpdateInspection(UpdateInspectionCommand request)
        {
            try
            {
                return await _mediator.Send(request);
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, "更新检药单失败");
                return new ApiResult<int>
                {
                    Code = ApiEnum.失败,
                    Message = $"更新失败：{ex.Message}",
                    Data = 0
                };
            }
        }

        #endregion

        #region 查看已发药品模块

        /// <summary>
        /// 获取已发药品列表（用于查看已发药品模块）
        /// 支持按时间筛选（今天/本周/本月/今年/全部）和患者信息筛选
        /// </summary>
        [HttpGet]
        public async Task<ApiResult<List<DispensedDrugDto>>> GetDispensedDrugs(
            string? cardNumber = null,
            string? patientName = null,
            string? drugName = null,
            DateTime? startDate = null,
            DateTime? endDate = null,
            string? timeFilterType = null)
        {
            try
            {
                var query = new GetDispensedDrugsQuery
                {
                    CardNumber = cardNumber,
                    PatientName = patientName,
                    DrugName = drugName,
                    StartDate = startDate,
                    EndDate = endDate,
                    TimeFilterType = timeFilterType
                };
                return await _mediator.Send(query);
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, "查询已发药品列表失败");
                return new ApiResult<List<DispensedDrugDto>>
                {
                    Code = ApiEnum.失败,
                    Message = $"查询失败：{ex.Message}",
                    Data = new List<DispensedDrugDto>()
                };
            }
        }

        #endregion
    }
}

